package org.SMSReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class Receiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// ---get the SMS message passed in---
		String str = getSMS(intent);

		// ---display the new SMS message---
		Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

		// ---create new Intent for MySMS class---
		Intent in = new Intent();
		in.setClass(context, MySMS.class);

		// ---set flags
		in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);

		// ---add SMS text to the Intent Extras---
		in.putExtra(MySMS.message, str);

		// ---start new activity---
		context.startActivity(in);
		
		getSMS(null);
	}

	/**
	 * Given the incoming Intent retrieves the SMS text
	 * 
	 * @param intent
	 * @return
	 */
	private String getSMS(Intent intent) {
		if (intent == null)
			return null;	
		
		// ---retrieve Extras---
		Bundle bundle = intent.getExtras();
		SmsMessage[] msgs = null;
		String str = "";

		// ---check if there is text---
		if (bundle == null)
			return null;

		// ---retrieve the SMS message received---
		Object[] pdus = (Object[]) bundle.get("pdus");
		if (pdus == null)
			return null;
		
		msgs = new SmsMessage[pdus.length];
		for (int i = 0; i < msgs.length; i++) {
			msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
			str += msgs[i].getMessageBody().toString();
			str += "\n";		
		}
		
		
		

		return str;
	}
}